package com.tool_stdy.IO.NIO;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * Created by yan_li on 2017/1/10.
 */
public class NIOClientTest {

    SocketChannel client;

    Selector selector;
    ByteBuffer receive = ByteBuffer.allocate(1024);
    ByteBuffer send = ByteBuffer.allocate(1024);

    public NIOClientTest() throws IOException {
        client = SocketChannel.open();
        client.configureBlocking(false);
        client.connect(new InetSocketAddress(8080));
        System.out.println("客户端已启动:" + 8080);

        selector = Selector.open();

        //客户端告诉selector可以建立链接了
        client.register(selector, SelectionKey.OP_CONNECT);
    }

    public static void main(String[] args) throws IOException {
        new NIOClientTest().session();
    }

    public void session() throws IOException {
        //先要判断是否已经建立起链接了
        if (client.isConnectionPending()) {
            client.finishConnect();
            //告诉选择器可以写东西了
            client.register(selector, SelectionKey.OP_WRITE);
            System.out.println("请在控制台登记姓名:");
        }
        //process("张三");
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String name = scan.nextLine();
            if (StringUtils.isBlank(name)) {
                continue;
            }
            process(name);
        }
    }

    public void process(String name) throws IOException {
        boolean unFinsih = true;
        while (unFinsih) {
            int i = selector.select();
            if (i <= 0) {
                continue;
            }
            for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
                SelectionKey key = it.next();
                if (key.isWritable()) {
                    send.clear();
                    send.put(name.getBytes());
                    send.flip();
                    client.write(send);
                    client.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    receive.clear();
                    int len = client.read(receive);
                    if (len > 0) {
                        receive.flip();
                        System.out.println("接受服务端消息:" + new String(receive.array(), 0, len));
                    }
                    client.register(selector, SelectionKey.OP_WRITE);
                    unFinsih = false;
                }
                it.remove();
            }
        }
    }
}
